package org.egrit.geometry;

import com.vividsolutions.jts.geom.Coordinate;
import com.vividsolutions.jts.geom.GeometryFactory;
import com.vividsolutions.jts.geom.Point;
import com.vividsolutions.jts.geom.Polygon;

/**
 * General utility methods applicable to JTS Geometry objects.
 * 
 * @author michael
 */
public class GeometryUtils {
    private static GeometryFactory GEOMETRY_FACTORY = new GeometryFactory();
    
    public static GeometryFactory getGeometryFactory() {
        return GEOMETRY_FACTORY;
    }
    
    /**
     * Calculates the inverse Laurance shape index for a polygon. Calculated as 
     * {@code (2 * sqrt(pi * A)) / P}
     * 
     * @param poly input polygon
     * 
     * @return shape index between 0 and 1
     * 
     * @throws IllegalArgumentException if poly is null, empty or contains any holes
     */
    public static double getShapeIndex(Polygon poly) {
        if (poly == null || poly.isEmpty()) {
            throw new IllegalArgumentException("polygon must not be null or empty");
        }
        
        if (poly.getNumInteriorRing() > 0) {
            throw new IllegalArgumentException("polygon must not contain holes");
        }
        
        double perim = poly.getExteriorRing().getLength();
        double area = poly.getArea();
        
        return 2 * Math.sqrt(Math.PI * area) / perim;
    }

    public static boolean pointInPolygon(Polygon poly, double x, double y) {
        Point p = GEOMETRY_FACTORY.createPoint(new Coordinate(x, y));
        return poly.contains(p);
    }
}
